<template>
  <el-main>
    <p></p>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input
            v-model="search"
            placeholder="请输入用户编号"
            clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchhistorys" >
          <el-icon><Search /></el-icon>查询
        </el-button>
        <el-button type="primary" @click="dialogVisible = true">
          <el-icon><Plus /></el-icon>添加
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible" title="添加" width="500">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="用户编号">
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="预缴费用">
          <el-input v-model="form.prNum" />
        </el-form-item>
        <el-form-item label="缴前余额">
          <el-input v-model="form.nbalance" />
        </el-form-item>
        <el-form-item label="缴后余额">
          <el-input v-model="form.newBalance" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-input v-model="form.type" />
        </el-form-item>
        <el-form-item label="预缴费时间">
          <el-input v-model="form.prPaytime" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addPrePay">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <p></p>
    <el-table :data="data.records" class="table" style="width: 99%" border>
      <el-table-column label="预缴费记录编号">
        <template #default="scope">
          <span>{{ scope.row.preId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户编号">
        <template #default="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名">
        <template #default="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预缴费用">
        <template #default="scope">
          <span>{{ scope.row.prNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴前余额">
        <template #default="scope">
          <span>{{ scope.row.nbalance }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴后余额">
        <template #default="scope">
          <span>{{ scope.row.newBalance }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式">
        <template #default="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预缴费时间">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon><Timer /></el-icon>
            <span style="margin-left: 10px">{{ scope.row.prPaytime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisibleEdit" title="修改" width="500">
      <el-form :model="edit" label-width="auto" style="max-width: 600px">
        <el-form-item label="用户编号">
          <el-input v-model="edit.userId" />
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="edit.username" />
        </el-form-item>
        <el-form-item label="预缴费用">
          <el-input v-model="edit.prNum" />
        </el-form-item>
        <el-form-item label="缴前余额">
          <el-input v-model="edit.nbalance" />
        </el-form-item>
        <el-form-item label="缴后余额">
          <el-input v-model="edit.newBalance" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-input v-model="edit.type" />
        </el-form-item>
        <el-form-item label="预缴费时间">
          <el-input v-model="edit.prPaytime" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取消</el-button>
          <el-button type="primary">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <p></p>
    <div style="margin-top: 10px;">
      <el-button mb-2 @click="toggle" class="switch">Switch Language</el-button>
      <br />
      <el-config-provider :locale="locale">
        <el-col span="8" :offset="5">
          <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              @current-change="handlePageChange"
              background
              layout="prev, pager, next, jumper"
              :total="total"
          />
        </el-col>
      </el-config-provider>
    </div>
  </el-main>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from "vue";
import axios from "axios";
import { Delete, Edit, Search, Plus, Timer } from "@element-plus/icons-vue";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import en from 'element-plus/dist/locale/en.mjs';
// import { ElMessage } from "element-plus";

const language = ref('zh-cn');
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en));
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示10条数据
const total = ref(0);
const search = ref('');
const toggle = () => {
  language.value = language.value === 'zh-cn' ? 'en' : 'zh-cn';
};
const tableData = ref<User[]>([]);
interface User {
  preId: number;
  userId: number;
  username: string;
  prNum: number;
  nbalance: number;
  newBalance: number;
  type: string;
  prPaytime: string;
}
let data = reactive({
  record: {
    preId: '',
    userId: '',
    username: '',
    prNum: '',
    nbalance: '',
    newBalance: '',
    type: '',
    prPaytime: '',
  },
  records: [] as User[]
});

const fetchhistorys = async () => {
  try {
    const response = await axios.get('http://localhost:8080/prePay/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        search: search.value
      }
    });
    data.records = response.data.data.records;
    total.value = response.data.data.total;
  } catch (error) {
    console.error('Error fetching water prices:', error);
  }
};

const handleEdit = (index: number, row: User) => {
  Object.assign(edit, row);
  dialogVisibleEdit.value = true;
};

const handleDelete = (index: number, row: User) => {
  deletePrePay(row.preId);
};

const dialogVisible = ref(false);
const dialogVisibleEdit = ref(false);

const formInline = reactive({
  user: "",
  region: "",
  date: "",
});


const addPrePay = async () => {
  try {
    const response = await axios.post('http://localhost:8080/prePay/add', form);
    if (response.data) {
      ElMessage.success({
        message: '添加成功',
        type: 'success',
      });
      fetchhistorys();
      dialogVisible.value = false;
    }
  } catch (error) {
    console.error("Error adding data:", error);
    ElMessage.error({
      message: '添加失败',
      type: 'error',
    });
  }
};

const deletePrePay = async (id: number) => {
  try {
    const response = await axios.delete(`http://localhost:8080/prePay/delete/${id}`);
    if (response.data) {
      ElMessage.success({
        message: '删除成功',
        type: 'success',
      });
      fetchhistorys();
    }
  } catch (error) {
    console.error("Error deleting data:", error);
    ElMessage.error({
      message: '删除失败',
      type: 'error',
    });
  }
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchhistorys();
};

const onSubmit = () => {
  fetchhistorys();
};

const form = reactive({
  preId: '',
  userId: '',
  username: '',
  prNum: '',
  nbalance: '',
  newBalance: '',
  type: '',
  prPaytime: ''
});

const edit = reactive({
  preId: '',
  userId: '',
  username: '',
  prNum: '',
  nbalance: '',
  newBalance: '',
  type: '',
  prPaytime: ''
});

onMounted(() => {
  let localUser = localStorage.getItem('user');
  if (localUser) {
    let data = JSON.parse(localUser);
    data.record = data;
  }
  // 在组件挂载时调用获取数据的函数
  fetchhistorys();
});
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.switch {
  display: none;
}
</style>